﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class MT5OrderController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;

        public MT5OrderController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, long? login=null, long? orderNumber = null, string transactionType = "", string tradingVariety = "", string creationTime = "")
        {
            ListResult res = new ListResult();
            try
            {
                var data = from y in _context.Mt5Orders
                           join m in _context.Mt5Users on y.Login equals m.Login
                           join c in _context.CrmUsers on m.CrmId equals c.Id
                           select new
                           {
                               //fullName = _context.Mt5Users.Any(mu => mu.Login == y.Login) ? _context.CrmUsers.Where(up => up.Id == _context.Mt5Users.First(mu => mu.Login == y.Login).CrmId).Select(k => k.Name + "/" + k.LoginName).FirstOrDefault() : "",
                               fullName = c.Name,
                               loginName = c.LoginName,
                               tradingAccount = y.Login,
                               transactionType = y.EnOrderType,
                               tradingVariety = y.Symbol,
                               volume = y.VolumeInitial,
                               orderNumber = y.Order,
                               explanatoryNote = y.Comment,
                               priceOrder = y.PriceOrder.ToString("#,##0.00") ,
                               timeSetupMsc = y.TimeSetup * 1000 - 8 * 3600 * 1000,
                               priceCurrent = y.PriceCurrent.ToString("#,##0.00") ,
                               createDate = y.CreateDate,
                               priceSl = y.PriceSl.ToString("#,##0.00") ,
                               priceTp = y.PriceTp.ToString("#,##0.00") ,
                               timeExpiration = y.TimeExpiration * 1000 - 8 * 3600 * 1000
                           };
                if (login != null)
                {
                    data = data.Where(k => k.tradingAccount == login);
                }
                if (orderNumber != null)
                {
                    data = data.Where(k => k.orderNumber == orderNumber);
                }
                if (!string.IsNullOrEmpty(transactionType))
                {
                    data = data.Where(k => k.transactionType == transactionType);
                }
                if (!string.IsNullOrEmpty(tradingVariety))
                {
                    data = data.Where(k => k.tradingVariety.Contains(tradingVariety));
                }
                if (!string.IsNullOrEmpty(creationTime) && creationTime.Contains(" - "))
                {
                    string[] registrationTimes = creationTime.Split(new string[] { " - " }, StringSplitOptions.None);
                    DateTime startTime = Convert.ToDateTime(registrationTimes[0]);
                    DateTime endTime = Convert.ToDateTime(registrationTimes[1]);
                    data = data.Where(k => k.createDate > startTime && k.createDate < endTime);
                }
                res.Code = 0;
                res.Count = data.Count();
                res.Data = await data.OrderByDescending(k => k.createDate).Skip((page - 1) * limit).Take(limit).ToListAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 交易类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetActions()
        {
            ListResult res = new ListResult();
            try
            {
                var data = _context.Mt5Orders.OrderBy(k => k.EnOrderType).Select(k => k.EnOrderType).Distinct().ToList();
                res.Code = 0;
                res.Count = data.Count();
                res.Data = data.ToList();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 交易品种
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetSymbols()
        {
            ListResult res = new ListResult();
            try
            {
                var data = _context.Mt5Orders.OrderBy(k => k.Symbol).Select(k => k.Symbol).Distinct().ToList();
                res.Code = 0;
                res.Count = data.Count();
                res.Data = data.ToList();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
    }
}
